import { goodslist,goodscount } from "../../../request/api"
interface StateGoods {
    goodsInfo:Array<object>
 }
interface StateSize{
    size:number
}
interface StateCount{
    count:number
}
interface StatePage{
    page:number
}
const state = {
    goodsInfo: [],
    size: 3,//页面显示的条数
    page: 1, //页码初始值
    count: 0  //总数

}
const getters = {
    getGoods(state:StateGoods) {
        return state.goodsInfo
    },
      //返回总数
    getCount(state:StateCount) {
        return state.count
    },
    //返回当前显示条数
    getSize(state:StateSize) {
        return state.size
    }


}
const mutations = {
    REQ_GOODSINFO(state:StateGoods,payload:any){
        state.goodsInfo = payload
    },
    REQ_GETCOUNT(state:StateCount,payload:any){
        state.count = payload
    },
    //修改页码
    CHANGE_PAGE(state:StatePage,payload:any){
        state.page = payload
    }

}
const actions = {
    //获取列表
    getGoodsInfoActions(context:any){
        goodslist({
            size:context.state.size,
            page:context.state.page
        })
        .then((res:any)=>{
            // console.log(res);
            if(res.code==200){
                context.commit("REQ_GOODSINFO",res.list)
               if(context.state.page != 1 && res.length ==0){
                context.dispatch("changePageAction",context.state.page-1)
               }
            }
        })
    },
      //封装一个获取总数的行动
      getCountAction(context:any){
        goodscount()
        .then((res:any)=>{
            // console.log(res,'总数哈哈哈');
            if(res.code==200){
                context.commit('REQ_GETCOUNT',res.list[0].total)
            }
        })
    },
    //封装一个切换页码的行动
    changePageAction(context:any,payload:any){
        //第一、当用户切换页码，我们要修改page
        context.commit('CHANGE_PAGE',payload)
        //第二、重新调用列表
        context.dispatch('getGoodsInfoActions')
    }


}
export default {
    state,
    getters,
    mutations,
    actions,
    namespaced:true
}